<?php
/**
 * 公告
 */
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Announ;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class AnnounController extends Controller
{
    public $v = 'admin.announ.';
	public $paginate = 15;

	/**
	 * 公告列表
	 * @param Request $request
	 * @return type
	 */
	public function index(Request $request, Announ $announ){
		$search = $request->input('search');
		$keyword = $request->input('keyword');
		
		$builder = $announ->orderBy('id', 'desc');
		//搜索
		if(!empty($search) && !empty($keyword)) {
			$builder = $builder->where($search, 'like', '%'.$keyword.'%');
		}		
        $announ = $builder->paginate($this->paginate);	
		return view($this->v . 'index', compact('search', 'keyword', 'announ'));
	}
	/**
	 * 公告添加
	 * @return type
	 */
	public function create()
    {
        return view($this->v . 'create');
    }
	/**
	 * 公告添加请求
	 * @return type
	 */
	public function createadd(Request $request, Announ $announ){		
		$params = $request->all();
		$validator = Validator::make($params, [
			'title' => 'required',
            'content' => 'required',
           
        ],[
			'title.required' => '请输入标题',			
            'content.required' => '请输入内容',
        ]);
        $error = $validator->errors()->first();
		if ($error) {
			return ajaxError($error);
		}
		
		$params['created_at'] = date('Y-m-d H:i:s');
        $rest = Announ::create($params);
		if(!$rest) {
			return ajaxError();
		}
		return ajaxSuccess();		
	}
	/**
	 * 公告修改模板
	 * @param type $id
	 * @return type
	 */
	public function edit(Request $request, $id)
    {
        $announ = Announ::where('id', $id)->first();
        return view($this->v . 'edit', compact('announ'));
    }
	/**
	 * 公告修改程序
	 * @param Request $request
	 * @param 
	 * @return type
	 */
    public function update(Request $request, Announ $announ, $id)
    {
		$params = $request->all();
		$validator = Validator::make($params, [
			'title' => 'required',
            'content' => 'required',
           
        ],[
			'title.required' => '请输入标题',			
            'content.required' => '请输入内容',
        ]);
        $error = $validator->errors()->first();
		if ($error) {
			return ajaxError($error);
		}
		$params['updated_at'] = date('Y-m-d H:i:s');
		$res = $announ->where('id', $id)->update($params);
        if (!$res) {
            return ajaxError();
        }
		return ajaxSuccess();
    }
	/**
	 * 公告删除
	 * @param Request $request
	 * @param 
	 * @return type
	 */
	public function delete(Request $request, $id)
    {
        $res = $annu = Announ::where('id', $id)->delete();
        if (!$res) return ajaxError();
        return ajaxSuccess();
    }
}
